const { spawn } = require('child_process');
const chokidar = require('chokidar')
const { resolve } = require('path')
require('dotenv/config')

function runtime(binary, array, success = function() {}) {
    let child = null
    let timer = null
    function run() {
        if (timer !== null) {
            return;
        }
        timer = setTimeout(() => {
            clearTimeout(timer)
            timer = null;
        }, 30)
        if (child) {
            child.kill()
        }
        child = spawn(binary, array, {
            cwd: resolve(),
            env: process.env,
        })
        child.stdout.on('data', function (buffer) {
            console.log(buffer.toString('utf-8'))
            if (/Found 0 errors\. Watching for file changes/.test(buffer.toString('utf-8'))) {
                success()
            }
        })
        child.stderr.on('data', err => {
            console.log(err.toString('utf-8'))
        })
    }
    return run
}
// backend
const backendRuntime = runtime('node', ['dist/index.js'])
const tscWatch = runtime('npx', ['tsc', '-w'], function() {
    backendRuntime()
})
tscWatch()
